#ifndef VIDEORECEIVER_H
#define VIDEORECEIVER_H

#include <QObject>
#include <QUdpSocket>
#include <QImage>
#include <QThread>
#include <QTimer>
#include <QNetworkInterface>

#include "common.h"
#include "gstvideoplayer.h"

class ReceiveWork;
class VideoReceiver : public QObject
{
    Q_OBJECT
public:
    explicit VideoReceiver(QWidget* control, quint16 listenPort, QString ip, QString infName,
                           int bindWay, QObject *parent = nullptr);
    ~VideoReceiver();

    void init();
    void startReceiving();
    void stopReceiving();
    void resetSettings(QString ip, quint16 listenPort, QString m_infName, int bindWay);

    FrameQueue m_frameQueue;       //全局接收队列(线程安全)

signals:
    void frameReceived(const QImage &image);
    void sig_start();
    void sig_stop();
    void sig_init();
    void sig_close();
    void sigSendDataToSave(const QByteArray &data, QString ipSrc, quint16 portSrc);  //转发后存储
    void sigFrameAvailable(const QImage &image);
    void sigSrcIP(QString);
    void sigVideoInfoChanged(int width, int height, int fps);

private:
    QThread *m_recThread;
    ReceiveWork *m_recWork;
    bool initRet;
    QTimer *m_timer;
    quint16 m_listenPort;           //组播绑定的端口
    QString m_ip;                   //组播绑定的ip
    QString m_infName;              //组播绑定的网卡名
    QWidget *m_control;
    int m_bindWay;                  //绑定udp的接收方法
    GstVideoPlayer *m_player;

public slots:
    void onTimer();
};

class ReceiveWork : public QObject
{
    Q_OBJECT
public:
    ReceiveWork(quint16 listenPort, QString ip, QString infName, FrameQueue* frameQueue, int bindWay) {
        m_listenPort = listenPort;
        m_ip = ip;
        m_infName = infName;
        m_frameQueue = frameQueue;
        m_bindWay = bindWay;
    }

    void setNetInfo(QString ip, quint16 port, QString infName);

public slots:
    void init();
    void onReceive();
    void startReceiving();
    void stopReceiving();
    void closeAll();

signals:
    void sig_initRet(bool);
    void frameToGStream(const QByteArray &data);
    void sigSendDataToSave(const QByteArray &data, QString ipSrc, quint16 portSrc);  //转发后存储
    void sigSrcIP(QString);

private:
    QUdpSocket *m_socket = nullptr;

    bool m_isReceiving;
    QByteArray m_dataGramH264;      //存储h264数据

    quint16 m_listenPort;           //组播绑定的端口
    QString m_ip;                   //组播绑定的ip
    QString m_infName;              //组播绑定的网卡名
    FrameQueue *m_frameQueue;       //接收队列
    int m_bindWay;                  //udp接收绑定方法

    int timeCount = 0;

    void initSingleUdp();   //单播方式初始化
    void initMultiUdp();    //组播方式初始化
    void initBroastUdp();   //广播方式初始化
};

#endif // VIDEORECEIVER_H    
